package com.emm.yixun.website.controller.base;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.UserResourcesDto;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.system.service.MerchantResourcesServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.mybatis.Page;
import com.emm.yixun.website.common.utils.base.UuidUtil;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.common.utils.webpage.PageData;
import com.emm.yixun.website.constant.EhcacheConstant;
import com.emm.yixun.website.service.CacheUtils;
import com.emm.yixun.website.service.system.resources.ResourcesService;



public class BaseController<T> {
	
	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	public ResourcesService resourcesService;
	
	@Autowired
	public MerchantResourcesServiceFacade merchantResourcesServiceFacade;
	
	@Autowired
	public CacheUtils cacheUtils;
	
	
	/**
	 * 得到PageData
	 */
	public PageData getPageData(){
		return new PageData(this.getRequest());
	}
	
	/**
	 * 得到ModelAndView
	 */
	public ModelAndView getModelAndView(){
		return new ModelAndView();
	}
	
	public AjaxRes getAjaxRes(){
		return new AjaxRes();
	}
	
	/**
	 * 得到request对象
	 */
	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();	
		return request;
	}

	/**
	 * 得到32位的uuid
	 * @return
	 */
	public String get32UUID(){	
		return UuidUtil.get32UUID();
	}
	
	/**
	 * 得到分页列表的信息 
	 * @param <T>
	 */
	@SuppressWarnings("hiding")
	public <T> Page<T> getPage(){	
		return new Page<T>();
	}
	
	public static void logBefore(Logger logger, String interfaceName){
		logger.info("");
		logger.info("start");
		logger.info(interfaceName);
	}
	
	public static void logAfter(Logger logger){
		logger.info("end");
		logger.info("");
	}
	
	public void removeResourcesCache(String roleId){
		User user = ShiroUtil.getCurrentUser();
		String menuCacheKey=String.format(EhcacheConstant.MERCHANT_ROLE_MENU_CACHE_KEY, String.valueOf(user.getMerchantId()),roleId);
		String buttonCacheKey=String.format(EhcacheConstant.MERCHANT_ROLE_BUTTON_CACHE_KEY, String.valueOf(user.getMerchantId()),roleId);
		cacheUtils.remove(EhcacheConstant.ACTIVE_SESSIONS_CACHE,menuCacheKey);
		cacheUtils.remove(EhcacheConstant.ACTIVE_SESSIONS_CACHE,buttonCacheKey);
	}
	
	
	//查询PC端菜单资源
	public List<com.emm.yixun.common.model.Resources> getRoleMenuResources(){
		User user = ShiroUtil.getCurrentUser();
		List<com.emm.yixun.common.model.Resources> menus = new ArrayList<com.emm.yixun.common.model.Resources>();
		// 获得用户Id
		UserResourcesDto userResourcesDto = new UserResourcesDto();
		userResourcesDto.setResourcesLevel("0");
		//pc端标示
		userResourcesDto.setResourcesType("1");
		userResourcesDto.setMerchantId(user.getMerchantId());
		Long roleId=user.getRoleId();
		//默认管理员
		String roleIdStr=EhcacheConstant.ADMIN_ROLE_ID;
		//系统管理员角色ID为null,当roleId不为null时，则认为是普通用户
		if (!user.getIsAdmin().equals("1")){
			roleIdStr=String.valueOf(roleId);
		}
		String cacheKey=String.format(EhcacheConstant.MERCHANT_ROLE_MENU_CACHE_KEY, String.valueOf(user.getMerchantId()),roleIdStr);
		Object object=cacheUtils.get(EhcacheConstant.ACTIVE_SESSIONS_CACHE,cacheKey);
		if(null==object){
			ResponseList<com.emm.yixun.common.model.Resources> responseList =null;
			if (!user.getIsAdmin().equals("1")) {
				userResourcesDto.setRoleId(String.valueOf(user.getRoleId()));
				responseList = merchantResourcesServiceFacade.findRoleResources(userResourcesDto);
			}else{
				responseList = merchantResourcesServiceFacade.findUserResources(userResourcesDto);
			}
			
			if (responseList.isSuccess()) {
				menus = responseList.getEntity();
				cacheUtils.put(EhcacheConstant.ACTIVE_SESSIONS_CACHE,cacheKey, menus);
			}
		}else{
			menus = (List<com.emm.yixun.common.model.Resources>)object;
		}
		return menus;
	}
	//查询PC端按钮资源
	public List<com.emm.yixun.common.model.Resources> getRoleButtonResources(String parentCode){
		User user = ShiroUtil.getCurrentUser();
		List<com.emm.yixun.common.model.Resources> menus = new ArrayList<com.emm.yixun.common.model.Resources>();
		// 获得用户Id
		UserResourcesDto userResourcesDto = new UserResourcesDto();
		userResourcesDto.setResourcesLevel("1");
		//pc端标示
		userResourcesDto.setResourcesType("1");
		userResourcesDto.setMerchantId(user.getMerchantId());
		Long roleId=user.getRoleId();
		//默认管理员
		String roleIdStr=EhcacheConstant.ADMIN_ROLE_ID;
		//系统管理员角色ID为null,当roleId不为null时，则认为是普通用户
		if (!user.getIsAdmin().equals("1")){
			roleIdStr=String.valueOf(roleId);
		}
		String cacheKey=String.format(EhcacheConstant.MERCHANT_ROLE_BUTTON_CACHE_KEY, String.valueOf(user.getMerchantId()),roleIdStr);
		Object object=cacheUtils.get(EhcacheConstant.ACTIVE_SESSIONS_CACHE,cacheKey);
		if(null==object){
			ResponseList<com.emm.yixun.common.model.Resources> responseList = null;
			if (!user.getIsAdmin().equals("1")) {
				userResourcesDto.setRoleId(String.valueOf(user.getRoleId()));
				responseList = merchantResourcesServiceFacade.findRoleResources(userResourcesDto);
			}else{
				responseList = merchantResourcesServiceFacade.findUserResources(userResourcesDto);
			}
			if (responseList.isSuccess()) {
				menus = responseList.getEntity();
				cacheUtils.put(EhcacheConstant.ACTIVE_SESSIONS_CACHE,cacheKey, menus);
			}
		}else{
			menus = (List<com.emm.yixun.common.model.Resources>)object;
		}
		List<com.emm.yixun.common.model.Resources> menusList = new ArrayList<com.emm.yixun.common.model.Resources>();
		if(StringUtils.isNotBlank(parentCode)){
			List<com.emm.yixun.common.model.Resources> resultMeunList = new ArrayList<com.emm.yixun.common.model.Resources>();
			for(com.emm.yixun.common.model.Resources resources : menus){
				if(resources.getParentCode().equals(parentCode)){
					resultMeunList.add(resources);
				}
			}
			return resultMeunList;
		}else{
			return menus;
		}
	}
	
	
	/**
	 *菜单按钮权限
	 */
	public List<com.emm.yixun.common.model.Resources> getPermitBtn(String type){
		List<com.emm.yixun.common.model.Resources> perBtns=new ArrayList<com.emm.yixun.common.model.Resources>();	
		try {
			//首先获取缓存
			String parentCode=getPageData().getString("menu");
			perBtns=getRoleButtonResources(parentCode);
		} catch (Exception e) {
			logger.error(e.toString(),e);
		}
		return perBtns;
	}
	
	/**
	 *按钮权限数组
	 */
	public String getPermissionBtnArray(){
		String resultArray="[]";
		try {
			List<com.emm.yixun.common.model.Resources> perBtns=getRoleButtonResources(null);;
			JSONArray array=new JSONArray();
			for(com.emm.yixun.common.model.Resources btn : perBtns){
				if(StringUtils.isBlank(btn.getPermission()))continue;
				array.add(btn.getPermission());
			}
			resultArray=array.toJSONString();
		} catch (Exception e) {
			logger.error(e.toString(),e);
			resultArray="[]";
		}
		return resultArray;
	}
	/**
	 * 资源的权限（URl级别）
	 * @param type 资源类别(优化速度)
	 * @return
	 */
	protected boolean doSecurityIntercept(String type){
		try {
			String servletPath = getRequest().getServletPath();
			servletPath = StringUtils.substringBeforeLast(servletPath,".");// 去掉后面的后缀
			return doSecurityIntercept(type,servletPath);
		} catch (Exception e) {
			logger.error(e.toString(),e);
		}
		return false;
	}
	
	/**
	 * 资源的权限（URl级别,拥有第一级资源权限，这资源才能访问）
	 * @param type 资源类别(优化速度)
	 * @param url 第一级资源
	 * @return
	 */
	protected boolean doSecurityIntercept(String type,String url){
		try {
			User user=ShiroUtil.getCurrentUser();
			if(null==user){
				return false;
			}
			//超级管理员
			if(user.getIsAdmin().equals("1")){
				return true;
			}
			List<com.emm.yixun.common.model.Resources> userResources=new ArrayList<com.emm.yixun.common.model.Resources>();
			if(type.equals("0") || type.equals("1")){
				//当为菜单或者功能性资源统一为数据库标示的菜单资源
				type="0";
				userResources=getRoleMenuResources();
			}else if(type.equals("2")){
				type="1";
				userResources=getRoleButtonResources(null);
			}
			for(com.emm.yixun.common.model.Resources r : userResources){
				//当type=0时比对url 当type=1时比对权限标示(system:user:add)
				if(type.equals("0")){
					if(r!=null&&StringUtils.isNotBlank(r.getResourcesHref())){
						if(StringUtils.equals(r.getResourcesHref(),url)){
							return true;
						}
					}
				}else if(type.equals("1")){
					if(r!=null&&StringUtils.isNotBlank(r.getPermission())){
						if(StringUtils.equals(r.getPermission(),url)){
							return true;
						}
					}
				}
				
				
			}
		} catch (Exception e) {
			logger.error(e.toString(),e);
		}
		return false;
	}
	
	/**
	 * 返回json数据
	 */
	public static void resultJson(HttpServletResponse response,Object result)throws IOException{
		String resultString = JSONObject.toJSONString(result);
		response.setHeader("Content-type", "text/html;charset=UTF-8");  
		response.getWriter().write(resultString);
	}
}
